import axiosIns, { axiosOdata } from '../utils/axios';
import { detailData, typeData } from '../utils/mock';

/**
|--------------------------------------------------
| Constants
|--------------------------------------------------
*/
const GET_DETAIL = 'GET_DETAIL';
const GET_TYPE = 'GET_TYPE';
/**
|--------------------------------------------------
| Actions
|--------------------------------------------------
*/
export function getDetail({ id }) {
  return async (dispatch, getState) => {
    const res = await axiosIns({ url: '/getDetail', params: { id } });
    const { data } = res;
    dispatch(getDetailed(data));
  };
}

function getDetailed(data) {
  return {
    type: GET_DETAIL,
    baseInfo: data
  };
}
export function getTypes({ id }) {
  return async (dispatch, getState) => {
    const res = await axiosIns({ url: '/getTypes', params: { id } });
    const { data } = res;
    dispatch(getTypesed(data.type));
  };
}
function getTypesed(data) {
  data.sort(function(a, b) {
    return a.price - b.price;
  });
  const minPrice = data[0].price;
  const maxPrice = data[data.length - 1].price;
  const priceRange =
    minPrice == maxPrice ? minPrice : `${minPrice}-${maxPrice}`;
  return {
    type: GET_TYPE,
    types: data,
    minPrice,
    maxPrice,
    priceRange
  };
}

export function getSaleInfo({ id }) {
  return async (dispatch, getState) => {};
}
/**
|--------------------------------------------------
| Action Handlers
|--------------------------------------------------
*/
const ACTION_HANDLERS = {
  [GET_DETAIL]: (state, action) => {
    return { ...state, baseInfo: action.baseInfo };
  },
  [GET_TYPE]: (state, action) => {
    const { types, minPrice, maxPrice, priceRange } = action;
    return { ...state, types, minPrice, maxPrice, priceRange };
  }
};
/**
|--------------------------------------------------
| Reducer
|--------------------------------------------------
*/
export const initialState = {
  baseInfo: {},
  types: [],
  saleInfo: {},
  minPrice: 0,
  maxPrice: 0,
  priceRange: '--'
};

export default function(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type];

  return handler ? handler(state, action) : state;
}
